package com.plugin.plugin_jd_upgrade

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.annotation.NonNull
import com.jingdong.sdk.jdupgrade.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** PluginJdUpgradePlugin */
class PluginJdUpgradePlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private lateinit var result: Result

    private var handler: Handler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            this@PluginJdUpgradePlugin.result.success(
                mapOf(
                    "hasUpgrade" to msg.data.getBoolean("hasUpgrade"),
                    "message" to msg.data.getString("message"),
                    "version" to msg.data.getString("version")
                )
            )
        }
    }

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "plugin_jd_upgrade")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        this.result = result

        when (call.method) {
            "getPlatformVersion" -> {
                this.result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }
            "checkAndPop" -> {
                checkAndPop()
            }
            "checkUpdate" -> {
                checkUpdate()
            }
            "limitedCheckAndPop" -> {
                limitedCheckAndPop()
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    /**
     * 检查更新
     */
    private fun checkUpdate() {
        /***
         * 是否有新版本回调
         * hasUpgrade true: 有 false: 没有
         * message 升级提示消息
         * version 升级版本号
         */
        JDUpgrade.hasNewVersion { hasUpgrade, message, version ->
            val msg = Message()
            msg.data = Bundle().apply {
                putBoolean("hasUpgrade", hasUpgrade)
                putString("message", message)
                putString("version", version)
            }
            handler.sendMessage(msg)
        }
    }

    /**
     * 检查更新，有时间间隔的弹框
     */
    private fun limitedCheckAndPop() {
        //检查更新
        JDUpgrade.limitedCheckAndPop(object : UpgradeEventListener {
            override fun onShowRemindDialog(p0: RemindType?, p1: UpgradeType?) {

            }

            override fun onCloseRemindDialog(p0: RemindType?, p1: UpgradeType?) {
            }

            override fun onDownloadStart(p0: Boolean) {
            }

            override fun onDownloadFinish(p0: Boolean) {
            }

            override fun onMessage(p0: String?) {
                p0?.let {
                    Log.e("JD升级", it)
                }
            }
        })
    }

    /**
     * 检查更新并弹框
     */
    private fun checkAndPop() {
        //检查更新
        JDUpgrade.unlimitedCheckAndPop(object : UpgradeEventListener {
            override fun onShowRemindDialog(p0: RemindType?, p1: UpgradeType?) {

            }

            override fun onCloseRemindDialog(p0: RemindType?, p1: UpgradeType?) {
            }

            override fun onDownloadStart(p0: Boolean) {
            }

            override fun onDownloadFinish(p0: Boolean) {
            }

            override fun onMessage(p0: String?) {
                p0?.let {
                    Log.e("JD升级", it)
                }
            }
        })
    }


    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
